<template>
    <div class="comments">
      <h3>评论</h3>
      
      <form @submit.prevent="submitComment">
        <textarea style="width: 92%" v-model="newComment" placeholder="写下你的评论..." rows="3"></textarea>
        <button type="submit" style="position: relative; left: 280px">发布</button>
      </form>
      <ul>
        <li v-for="comment in comments" :key="comment._id" class="comment-item">
          <div class="comment-content">
            <p v-if="!isReply(comment.content)">
            <h4 style="line-height: 10px"> <img src="../../../state/image.png" style="width: 40px;border-radius: 50%"/> <span style="position: relative; top: -19px;">{{ comment.name }}</span>
            <span style="position: relative; left: -30px; font-size: xx-smaller; font-weight: 100;">
                {{`${new Date(comment.created_at).getFullYear()}年${String(new Date(comment.created_at).getMonth() + 1).padStart(2, '0')}月${String(new Date(comment.created_at).getDate()).padStart(2, '0')}日 ${String(new Date(comment.created_at).getHours()).padStart(2, '0')}:${String(new Date(comment.created_at).getMinutes()).padStart(2, '0')}`}}
            </span>
            </h4>
            <p class="contextp">{{ comment.content }}</p>
                </p>
            <div v-if="isReply(comment.content)" class="reply-content">
              <p>{{ comment.content }}</p>
            </div>
            <button @click="reply(comment._id)" v-if="!isReply(comment.content)" class="reply-button" style="background: none; color: blue">回复</button>
          </div>
          <ul v-if="comment.replies">
            <li v-for="reply in comment.replies" :key="reply._id" class="reply-item">
              <div class="comment-content">
                <h4>{{ reply.name }}</h4>
                <p>{{ reply.content }}</p>
              </div>
            </li>
          </ul>
        </li>
      </ul>
    </div>
  </template>

  <script setup>
import { ref } from 'vue';
import axios from 'axios';

const comments = ref([]);
const newComment = ref('');
const replyingTo = ref(null);

// 判断评论内容是否以“@回复”开头
const isReply = (content) => {
  return content.trim().startsWith('@回复');
};

// 获取评论列表
const fetchComments = async () => {
  try {
    const response = await axios.get('http://localhost:3000/comments');
    const list = response.data
    // .sort((a, b) => {
    //   // 假设 created_at 是 ISO 8601 格式的字符串
    //   const dateA = new Date(a.created_at);
    //   const dateB = new Date(b.created_at);
    //   return dateB - dateA; // 倒序排序
    // });
    comments.value = list;
    console.log(comments.value);
    
  } catch (error) {
    console.error('Error fetching comments:', error);
  }
};

// 提交新评论
const submitComment = async () => {
  if (newComment.value.trim() === '') return;

  const commentData = {
    name: '游客', // 这里可以替换为实际的用户昵称
    content: newComment.value,
    parent: replyingTo.value || null,
  };

  try {
    const response = await axios.post('http://localhost:3000/comments', commentData);
    comments.value.unshift(response.data);
    newComment.value = '';
    replyingTo.value = null;
    fetchComments()
  } catch (error) {
    console.error('Error submitting comment:', error);
  }
};

// 回复评论
const reply = (id) => {
  replyingTo.value = id;
  newComment.value = `@回复 ${comments.value.find(comment => comment._id === id).name} `;
};

// 在组件加载时获取评论
fetchComments();
</script>

<style scoped>
.contextp{
    width: 85%;
    word-wrap: break-word; /* 允许在单词内换行 */
    color: 
}
.comments {
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
}

.comments h3 {
  margin-bottom: 10px;
}

.comments ul {
  list-style-type: none;
  padding: 0;
}

.comment-item {
}
.comments button[data-v-f2fe6119]{
    background-color: rgb(255, 255, 255) !important;
    color: blue;
}
.comment-content {
  border-radius: 4px;
  padding: 10px;
  position: relative;
}

.reply-content {
  margin-left: 40px; /* 缩进宽度 */
  word-wrap: break-word; /* 自动换行 */
  border-left: 2px solid #ccc; /* 左侧边框 */
  padding-left: 10px; /* 左侧内边距 */
  margin-top: 5px; /* 上边距 */
  margin-bottom: 5px; /* 下边距 */
  background-color: #f9f9f9;
}

.reply-item {
  margin-left: 30px; /* 缩进宽度 */
}

.reply-item .comment-content {
  background-color: #f9f9f9;
  padding: 5px;
  border-radius: 4px;
  word-wrap: break-word; /* 自动换行 */
}

.comment-content h4 {
  margin: 0 0 5px;
  font-size: 16px;
}

.comment-content p {
  margin: 0 0 5px;
}

.reply-button {
  padding: 0; /* 取消内边距 */
  margin-left: 5px; /* 与文本的小间隔 */
  font-size: 12px; /* 字体变小 */
  color: #007bff; /* 按钮文字颜色，可以自定义 */
  background: none; /* 取消背景 */
  border: none; /* 取消边框 */
  cursor: pointer; /* 鼠标悬停时显示指针 */
  text-decoration: underline; /* 文字下划线，增加可点击的视觉效果 */
  position: relative;
  right: -270px;
  top: -20px;
}

/* 表单样式 */
.comments textarea {
  width: 100%;
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.comments button {
  padding: 5px 10px;
  cursor: pointer;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 4px;
  transition: background-color 0.3s ease;
}

.comments button:hover {
  background-color: #45a049;
}
</style>